import React, {useEffect, useState} from "react";
import {
    Text,
    TouchableOpacity,
    FlatList, ActivityIndicator, Alert,
} from "react-native";
import styles from "./index.style";
import {useTheme} from "@/contexts/ThemeContext";
import CustomEmojiPreviewer
    from "@/components/Chat/ChatDetail/BottomBar/EmojiPanelDrawer/CustomEmojiList/CustomEmojiPreviewer";
import {useEmojiActions, useEmojiState} from "@/hooks/emoji/user-emoji";
import {UserEmojiPackItemType} from "@/types/user-emoji";
import * as ImagePicker from "expo-image-picker";
import {FileFormDataType} from "@/types/file-upload";

interface CustomEmojiListProps {
    onSelectEmoji?: (emoji: UserEmojiPackItemType) => void;
}

export default function CustomEmojiList({onSelectEmoji}: CustomEmojiListProps) {
    const {colors} = useTheme();
    const {loading, emojiItems} = useEmojiState()
    const {checkOrUpdateEmojiItems, addEmojiItem} = useEmojiActions()

    useEffect(() => {
        checkOrUpdateEmojiItems();
    }, []);

    const openPicturePicker = async () => {
        let results = await ImagePicker.launchImageLibraryAsync({
            mediaTypes: ['images'],
            allowsMultipleSelection: false,
            quality: 1
        });
        if (results.canceled) {
            return;
        }
        if (results.assets && results.assets.length > 0) {
            // 取第一个选中的图片
            const asset = results.assets[0];
            // 构建 FormData
            const formData = new FormData();
            const uri = asset.uri;
            const fileName =  asset.fileName || `file_${uri.split("/").pop()}`; // 防止 fileName 为 undefined
            const fileType = asset.mimeType || "application/octet-stream"; // 更健壮
            const fileData: any = {
                uri,
                name: fileName,
                type: fileType,
            };
            // 添加文件字段
            formData.append("file", fileData);
            // 调用上传方法
            await addEmojiItem(formData);
        }
    }


    const renderItem = (item: UserEmojiPackItemType) => (
        <CustomEmojiPreviewer key={item.id} data={item}
                              onSelectEmoji={(emoji) => onSelectEmoji && onSelectEmoji(emoji)}/>
    );

    if (loading) {
        return <ActivityIndicator size="large" color={colors.primary} style={styles.loadingIndicator}/>
    }
    return (
        <FlatList
            style={styles.emojiList}
            data={[{id: "add"}, ...emojiItems]}
            keyExtractor={(item) => item.id}
            renderItem={({item}) =>
                item.id === "add" ? (
                    <TouchableOpacity style={styles.addButton}
                                      onPress={openPicturePicker}>
                        <Text style={styles.addButtonText}>+</Text>
                    </TouchableOpacity>

                ) : renderItem(item as UserEmojiPackItemType)
            }
            numColumns={6} // 4列网格
            contentContainerStyle={[styles.customGrid, {borderColor: colors.border.divider}]}
            showsVerticalScrollIndicator={false}
        />
    );
}
